/*
 * @Author: lihaogn
 * @Date: 2021-12-18 21:14:11
 * @LastEditTime: 2021-12-21 14:07:18
 * @LastEditor: lihaogn
 * @Description: 权限 service
 * @FilePath: \lix-admin-server\app\service\permission.js
 */
const Service = require("egg").Service;
const commonUtils = require("../utils/commonUtils");

class PermissionService extends Service {
  /**
   * @author: lihaogn
   * @Date: 2021-12-20 00:58:58
   * @description: 查询权限
   * @param {*}
   * @return {*}
   */
  async queryPermissions() {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Permission.findAll();
      return commonUtils.makeTree(res);
    } catch (err) {
      console.log("查询权限信息err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 01:02:31
   * @description: 新增权限
   * @param {*} name
   * @param {*} mark
   * @param {*} description
   * @param {*} parentId
   * @return {*}
   */
  async createPermission({ name, mark, type, description, parentId }) {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Permission.create({
        id: commonUtils.getUUID(),
        name,
        mark,
        type,
        description,
        parentId,
      });
      return res;
    } catch (err) {
      console.log("创建权限err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 01:02:39
   * @description: 修改权限
   * @param {*} id
   * @param {*} name
   * @param {*} mark
   * @param {*} description
   * @return {*}
   */
  async updatePermission(id, { name, mark, type, description }) {
    const { app } = this;
    try {
      // ========= Sequelize 写法 =========
      const res = await app.model.Permission.update(
        {
          name,
          mark,
          type,
          description,
        },
        {
          where: { id },
        }
      );
      return res.length;
    } catch (err) {
      console.log("修改权限err:", err);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 20:51:16
   * @description: 删除权限
   * @param {*} id
   * @return {*}
   */
  async deletePermission(id) {
    const { app } = this;

    try {
      const res = await app.model.Permission.destroy({
        where: {
          [app.Sequelize.Op.or]: [{ id }, { parentId: id }],
        },
      });
      return res;
    } catch (error) {
      console.log("deletePermission err", error);
      return false;
    }
  }
}

module.exports = PermissionService;
